﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DIS.Infrastructure.Entities.Entity;
using DIS.Tool.Framework;
using System.Web.Security;
using System.Web;
using DIS.Infrastructure.Entities;
using System.Data.SqlClient;
using System.Data;

namespace DIS.Portal.Biz
{
    public class UserBiz
    {
        public static User Login(string userName, string password, bool rememberMe = false)
        {
            var user = new User().Find(c => c.UserName == userName);
            if (user != null)
            {
                if (user.Password == AesAlgorithm.Encrypt(password))
                {
                    if (!user.IsActivate)
                    {
                        return new User() { IsActivate = false };
                    }
                    FormsAuthentication.SetAuthCookie(userName, rememberMe);
                    return user;
                }


            }
            return null;
        }

        public static void LogOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }

        public static ItemListBox<User> GetAllUser(string userKey = "", int page = 0, int pageSize = 20)
        {
            var count = new User().Count(c => c.UserName.Contains(userKey) || c.RealName.Contains(userKey));

            var data = new User().FindAll(c => c.UserName.Contains(userKey) || c.RealName.Contains(userKey), c => c.UserName, page, pageSize);

            return new ItemListBox<User>(data).BuildPage(
                   count, page, pageSize, new PageParameter() { Style = "workspace" });

        }

        public static User SaveUser(User user)
        {
            if (user.Id > 0)
            {
                var userTemp = new User().Find(user.Id.ToString());
                userTemp.Birthday = user.Birthday;
                userTemp.Gender = user.Gender;
                userTemp.IdCardNo = user.IdCardNo;
                userTemp.Phone = user.Phone;
                userTemp.Photo = user.Photo;
                userTemp.QQ = user.QQ;
                userTemp.RealName = user.RealName;
                userTemp.SystemRole = user.SystemRole;
                userTemp.ProfessionName = user.ProfessionName;
                userTemp.DepartMentName = user.DepartMentName;
                userTemp.PostModify();
            }
            else
            { 
                user.IsActivate = true;
                user.PostAdd();
            }
            return user;
        }
    }
}
